//
//  SWGlobalPopupMenu.swift
//  UIcomnentTest2
//
//  Created by linhan on 2016/12/27.
//  Copyright © 2016年 test. All rights reserved.
//

import Foundation

enum SWGlobalPopupMenuAction
{
    case takePhoto
    case album
}

protocol SWGlobalPopupMenuDelegate:NSObjectProtocol
{
    func globalPopupMenuClicked(action:SWGlobalPopupMenuAction)
}

protocol SWGlobalPopupMenuDataSource:NSObjectProtocol
{
    var popupMenuController:AnyObject?{get set}
    func globalPopupMenuVerticalGrid() -> CGFloat
    func argumentForGlobalPopupMenu() -> Any?
}

protocol SWGlobalPopupMenu:SWGlobalPopupMenuDelegate,SWGlobalPopupMenuDataSource,SWTakePhotoViewControllerDelegate
{
    func presentTakePhotoViewController()
    func pushAlbumViewController()
}

extension SWGlobalPopupMenu where Self:UIViewController
{
    func globalPopupMenuSetup(container:UIView, rightMargin:CGFloat = 30, bottomMargin:CGFloat = 30)
    {
        let controller:PopupMenuController = PopupMenuController(container: container, rightMargin:rightMargin, bottomMargin:bottomMargin)
        controller.delegate = self
        popupMenuController = controller
    }
    
    func presentTakePhotoViewController()
    {
        let viewController = SWTakePhotoViewController()
        viewController.delegate = self
        let navigation = SWBaseNavigationController(rootViewController: viewController)
        present(navigation, animated: true, completion:nil)
    }
    
    func pushAlbumViewController()
    {
        navigationController?.pushViewController(SWAlbumViewController(), animated: true)
    }
    
    func takePhotoViewController(_ viewController:SWTakePhotoViewController, didFinishPicking images:[UIImage])
    {
        var count:Int = 0
        var results:[WriteImageCompletionResult] = []
        let event:SWKidEvent? = argumentForGlobalPopupMenu() as? SWKidEvent
        let writeImageAllCompletion = {
            for results in results
            {
                if let localIdentifier = results.localIdentifier, localIdentifier != ""
                {
                    SWAssetsManager.sharedManager().addAsset(localID: localIdentifier, event: event)
                }
            }
            print("相册写入成功")
        }
        
        for image in images
        {
            SWAssetsLibraryHelper.shared().writeImageDataToAlbum(image: image, albumName: SW.Config.DefaultAlbumName, completionHandler: { result in
                results.append(result)
                count += 1
                if count == images.count
                {
                    writeImageAllCompletion()
                }
            })
        }
    }
    
    
}

extension SWGlobalPopupMenuDataSource
{
    func globalPopupMenuVerticalGrid() -> CGFloat
    {
        return 12
    }
    
    func argumentForGlobalPopupMenu() -> Any?
    {
        return nil
    }
}

extension SWGlobalPopupMenuDelegate where Self:UIViewController
{
    func globalPopupMenuClicked(action:SWGlobalPopupMenuAction)
    {
        if action == .takePhoto
        {
            if let menu = self as? SWGlobalPopupMenu
            {
                menu.presentTakePhotoViewController()
            }
        }
        else if action == .album
        {
            if let menu = self as? SWGlobalPopupMenu
            {
                menu.pushAlbumViewController()
            }
        }
    }
}

class PopupMenuController:NSObject,SWPopupContainerDelegate
{
    weak var delegate:(SWGlobalPopupMenuDataSource & SWGlobalPopupMenuDelegate)?
    
    lazy private var _popupContainer:PopupContainer = PopupContainer()
    private var _globalCenter:CGPoint = CGPoint.zero
    private var _othersButtonIdentityCenter:CGPoint = CGPoint.zero
    
    
    private var _addBtn:UIButton = UIButton(type: .custom)
    private var _takePhotoBtn:UIButton = UIButton(type: .custom)
    private var _albumBtn:UIButton = UIButton(type: .custom)
    private var _buttonContainer:UIView = UIView()
    
    deinit
    {
        //print("DEINIT PopupMenuController")
    }
    
    init(container:UIView, rightMargin:CGFloat, bottomMargin:CGFloat) {
        super.init()
        
        _popupContainer.delegate = self
        _buttonContainer.clipsToBounds = true
        
        //[+]按钮
        _addBtn.setImage(UIImage(named:"main_btn_popupmenu"), for: .normal)
        _addBtn.sizeToFit()
        _addBtn.frame = CGRectMake(container.width - _addBtn.width - rightMargin, container.height - _addBtn.height - bottomMargin, _addBtn.width, _addBtn.height)
        _addBtn.addTarget(self, action: #selector(addBtnTapped), for: .touchUpInside)
        container.addSubview(_addBtn)
        
        _globalCenter = container.convert(_addBtn.frame, to: UIApplication.shared.keyWindow).center
        
        _takePhotoBtn.setImage(UIImage(named:"main_btn_camera"), for: .normal)
        _takePhotoBtn.sizeToFit()
        _takePhotoBtn.addTarget(self, action: #selector(takePhotoBtnTapped), for: .touchUpInside)
        _buttonContainer.addSubview(_takePhotoBtn)
        
        _albumBtn.setImage(UIImage(named:"main_btn_album"), for: .normal)
        _albumBtn.sizeToFit()
        _albumBtn.addTarget(self, action: #selector(albumBtnTapped), for: .touchUpInside)
        _buttonContainer.addSubview(_albumBtn)
    }
    
    func willPresentPopupContainer()
    {
        let buttons:[UIView] = [_takePhotoBtn, _albumBtn]
        let grid:CGFloat = delegate?.globalPopupMenuVerticalGrid() ?? 0
        //测算容纳这些按钮需要的高度
        var buttonContainerHeight:CGFloat = 0
        for button in buttons
        {
            buttonContainerHeight += button.height
        }
        buttonContainerHeight += CGFloat(buttons.count) * grid
        
        let buttonContainerWidth:CGFloat = _takePhotoBtn.width
        let buttonContainerY = _globalCenter.y - buttonContainerHeight - _addBtn.height * 0.5
        _buttonContainer.frame = CGRectMake(_globalCenter.x - buttonContainerWidth * 0.5, buttonContainerY, buttonContainerWidth, buttonContainerHeight)
        let buttonIdentityCenter:CGPoint = CGPointMake(buttonContainerWidth * 0.5, buttonContainerHeight)
        _othersButtonIdentityCenter = buttonIdentityCenter
        for button in buttons
        {
            button.center = buttonIdentityCenter
            button.alpha = 0
        }
        
        
        UIView.animate(withDuration: 0.2, animations: {
            self._addBtn.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI / 4))
            for (index,button) in buttons.enumerated()
            {
                let centerY:CGFloat = (button.height + grid) * CGFloat(index) + (button.height * 0.5)
                button.center = CGPointMake(buttonIdentityCenter.x, centerY)
                button.alpha = 1
            }
        })
    }
    
    func willDismissPopupContainer()
    {
        let buttons:[UIView] = [_takePhotoBtn, _albumBtn]
        UIView.animate(withDuration: 0.2, animations: {
            self._addBtn.transform = CGAffineTransform.identity
            for button in buttons
            {
                button.center = self._othersButtonIdentityCenter
                button.alpha = 0
            }
        })
    }
    
    @objc private func addBtnTapped()
    {
        _popupContainer.show(_buttonContainer, modelType:.clear)
    }
    
    @objc private func takePhotoBtnTapped()
    {
        _popupContainer.close(true)
        delegate?.globalPopupMenuClicked(action: .takePhoto)
    }
    
    @objc private func albumBtnTapped()
    {
        _popupContainer.close(true)
        delegate?.globalPopupMenuClicked(action: .album)
    }
    
    
    
}



